<script lang="ts" setup>
import { reactive, ref, watch } from "vue"
// import { reactive, ref, watch, toRaw } from "vue"
// import { type GetTableData } from "@/api/table/types/table"
import { ElMessage, ElMessageBox, type FormInstance, type FormRules, ElTree } from "element-plus"
import { CirclePlus, Refresh, RefreshRight, Search } from "@element-plus/icons-vue"
import { usePagination } from "@/hooks/usePagination"
import {
  CreateRoleRequestData,
  DeleteRoleRequestData,
  getMenuListApi,
  getRoleDetailApi,
  getRoleListApi,
  UpdateRoleRequestData
} from "@/api/system"
import { type GetTableData } from "@/api/system/types/admin"

defineOptions({
  // 命名当前组件
  name: "adminIndexPage"
})

//#region treeData
const newIds = ref([] as any[] | undefined | null)
const defaultIds = ref<any>(undefined)
const menuTreeData = ref<any>([])
const treeRef = ref<InstanceType<typeof ElTree>>()
const handleNodeClick = () => {}
const setCheckedNodes = (arr: any, val: any) => {
  const menuIds = val.checkedKeys
  formData.menu_id = ""
  formData.menu_id = menuIds.join(",")
  console.log("menuIds")
  console.log(menuIds)
  newIds.value = treeRef.value?.getCheckedNodes(false, true).map((i) => i.id)
  console.log("newIds")
  console.log(newIds)
}

//#endregion

const loading = ref<boolean>(false)
const dialogLoading = ref<boolean>(false)
const { paginationData, handleCurrentChange, handleSizeChange } = usePagination()

//#region 增
const is_enable = ref<boolean>(false)
const dialogVisible = ref<boolean>(false)
const formRef = ref<FormInstance | null>(null)
const formData = reactive({
  role_name: "",
  menu_id: "",
  is_enable: ""
})
const formRules: FormRules = reactive({
  role_name: [{ required: true, trigger: "blur", message: "请输入名称" }]
  // menu_id: [{ required: true, trigger: "blur", message: "请选择" }]
})
const handleCreate = () => {
  formRef.value?.validate((valid: boolean, fields) => {
    if (valid) {
      // formData.is_enable = is_enable.value ? 1 : 0
      if (currentUpdateId.value === undefined) {
        CreateRoleRequestData(formData)
          .then(() => {
            ElMessage.success("新增成功")
            getTableData()
          })
          .finally(() => {
            dialogVisible.value = false
          })
      } else {
        UpdateRoleRequestData({
          id: currentUpdateId.value,
          role_name: formData.role_name,
          menu_id: formData.menu_id,
          is_enable: formData.is_enable
        })
          .then(() => {
            ElMessage.success("修改成功")
            getTableData()
          })
          .finally(() => {
            dialogVisible.value = false
          })
      }
    } else {
      console.error("表单校验不通过", fields)
    }
  })
}
const handleCreateDialog = async () => {
  await getMenuTableListData()
  // defaultIds.value = ref([] as any[] | undefined | null)
  dialogVisible.value = true
}
const resetForm = () => {
  currentUpdateId.value = undefined
  is_enable.value = false
  formData.role_name = ""
  formData.menu_id = ""
  formData.is_enable = ""
  menuTreeData.value = []
  defaultIds.value = []
}
//#endregion

//#region 删
const handleDelete = (row: GetTableData) => {
  ElMessageBox.confirm(`正在删除用户：${row.role_name}，确认删除？`, "提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning"
  }).then(() => {
    DeleteRoleRequestData({ id: row.id }).then(() => {
      ElMessage.success("删除成功")
      getTableData()
    })
  })
}
//#endregion

//#region 改
const currentUpdateId = ref<undefined | string>(undefined)
const handleUpdate = async (row: GetTableData) => {
  await getMenuTableListData()
  await getDetail(row.id)
  currentUpdateId.value = row.id
  // formData.role_name = row.role_name
  dialogVisible.value = true
}
//#endregion

//#region 查
const tableData = ref<GetTableData[]>([])
const searchFormRef = ref<FormInstance | null>(null)
const searchData = reactive({
  role_name: ""
})
const getTableData = () => {
  loading.value = true
  getRoleListApi({
    pageNum: paginationData.currentPage,
    pageSize: paginationData.pageSize,
    role_name: searchData.role_name || undefined
  })
    .then((res) => {
      paginationData.total = res.data.total
      tableData.value = res.data.data
    })
    .catch(() => {
      tableData.value = []
    })
    .finally(() => {
      loading.value = false
    })
}
const getDetail = async (id: string) => {
  dialogLoading.value = true
  await getRoleDetailApi({
    id: id
  })
    .then((res) => {
      const arr: any = []
      defaultIds.value = []
      res.data.menuIds.forEach((item: any) => {
        if (!treeRef.value?.getNode(item).childNodes || !treeRef.value?.getNode(item).childNodes.length) {
          arr.push(item)
        }
      })
      is_enable.value = res.data.is_enable == 1
      console.log(arr)
      defaultIds.value = arr
      Object.assign(formData, res.data)
    })
    .catch((err) => {
      console.log(err)
    })
  dialogLoading.value = false
}

const getMenuTableListData = async () => {
  // loading.value = true
  const data = await getMenuListApi({})
  menuTreeData.value = data.data
  // loading.value = false
}
const handleSearch = () => {
  paginationData.currentPage === 1 ? getTableData() : (paginationData.currentPage = 1)
}
const resetSearch = () => {
  searchFormRef.value?.resetFields()
  handleSearch()
}
//#endregion

/** 监听分页参数的变化 */
watch([() => paginationData.currentPage, () => paginationData.pageSize], getTableData, { immediate: true })
</script>

<template>
  <div class="app-container">
    <el-card v-loading="loading" shadow="never" class="search-wrapper">
      <el-form ref="searchFormRef" :inline="true" :model="searchData">
        <el-form-item prop="role_name" label="名称">
          <el-input v-model="searchData.role_name" placeholder="请输入" />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" :icon="Search" @click="handleSearch">查询</el-button>
          <el-button :icon="Refresh" @click="resetSearch">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>
    <el-card v-loading="loading" shadow="never">
      <div class="toolbar-wrapper">
        <div>
          <el-button type="primary" :icon="CirclePlus" @click="handleCreateDialog()">新增</el-button>
          <!--          <el-button type="danger" :icon="Delete">批量删除</el-button>-->
        </div>
        <div>
          <!--          <el-tooltip content="下载">-->
          <!--            <el-button type="primary" :icon="Download" circle />-->
          <!--          </el-tooltip>-->
          <el-tooltip content="刷新当前页">
            <el-button type="primary" :icon="RefreshRight" circle @click="getTableData" />
          </el-tooltip>
        </div>
      </div>
      <div class="table-wrapper">
        <el-table :data="tableData">
          <el-table-column type="selection" width="50" align="center" />
          <el-table-column prop="role_name" label="名称" align="center" />
          <el-table-column prop="is_enable" label="状态" align="center">
            <template #default="scope">
              <el-tag v-if="scope.row.is_enable == 1" type="success" effect="plain">启用</el-tag>
              <el-tag v-else type="danger" effect="plain">禁用</el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="create_time" label="创建时间" align="center" />
          <el-table-column prop="enable_time" label="启用时间" align="center" />
          <el-table-column fixed="right" label="操作" width="150" align="center">
            <template #default="scope">
              <template v-if="scope.row.id != 1">
                <el-button type="primary" text bg size="small" @click="handleUpdate(scope.row)">修改</el-button>
                <el-button type="danger" text bg size="small" @click="handleDelete(scope.row)">删除</el-button>
              </template>
            </template>
          </el-table-column>
        </el-table>
      </div>
      <div class="pager-wrapper">
        <el-pagination
          background
          :layout="paginationData.layout"
          :page-sizes="paginationData.pageSizes"
          :total="paginationData.total"
          :page-size="paginationData.pageSize"
          :currentPage="paginationData.currentPage"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>
    <!-- 新增/修改 -->
    <el-dialog
      v-model="dialogVisible"
      :title="currentUpdateId === undefined ? '新增' : '修改'"
      @close="resetForm"
      width="80%"
      v-loading="dialogLoading"
    >
      <el-form ref="formRef" :model="formData" :rules="formRules" label-width="100px" label-position="left">
        <el-form-item prop="role_name" label="名称">
          <el-input v-model="formData.role_name" placeholder="请输入" />
        </el-form-item>
        <el-form-item prop="is_enable" label="状态">
          <el-radio-group v-model="formData.is_enable">
            <el-radio :label="1">启用</el-radio>
            <el-radio :label="0">禁用</el-radio>
          </el-radio-group>
          <!-- <el-switch v-model="is_enable" active-text="启用" inactive-text="未启用" /> -->
          <!--          <el-input v-model="formData.status" placeholder="请输入" />-->
        </el-form-item>
        <el-form-item prop="menu_id" label="菜单">
          <el-tree
            v-model="formData.menu_id"
            show-checkbox
            default-expand-all
            collapse-tags
            collapse-tags-tooltip
            node-key="id"
            highlight-current
            :default-checked-keys="defaultIds"
            ref="treeRef"
            :data="menuTreeData"
            @check="setCheckedNodes"
            @check-change="handleNodeClick"
          />
          <!--          <el-tree :data="menuTreeData" lazy show-checkbox @check-change="handleCheckChange" />-->
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleCreate">确认</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<style lang="scss" scoped>
.search-wrapper {
  margin-bottom: 20px;

  :deep(.el-card__body) {
    padding-bottom: 2px;
  }
}

.toolbar-wrapper {
  display: flex;
  justify-content: space-between;
  margin-bottom: 20px;
}

.table-wrapper {
  margin-bottom: 20px;
}

.pager-wrapper {
  display: flex;
  justify-content: flex-end;
}
</style>
